/* b_gen_asnprob.do - *****************************************************************************

	Generates the probability of assignment to each program

**************************************************************************************************/
set more off

local year "1997 1998 1999 2000 2001 2002 2003"
local grade "K0 K1"


foreach y of local year {
	foreach g of local grade {


		use "$stata_data_assignment/`y'/tracks`g'.dta", clear
		count
		*DROP OCCURS HERE
		drop if missing(pid)
		bys pid (maxpri) : replace maxpri = maxpri[1]
		bys pid (maxrand) : replace maxrand = maxrand[1]
		count
		drop if pcap==0
		count

		count if missing(maxrand,maxpri)

		bys pid : egen anyoffer = max(propose)
		replace maxpri = 99999999 if missing(maxpri) & anyoffer==0
		replace maxrand = 99999999 if missing(maxrand) & anyoffer==0

		gen subpri = prirank>maxpri
		gen suppri = prirank<maxpri
		gen marpri = prirank==maxpri

		if `y'==2006 {
			gen tau = maxrand/1000000000
		}
		else {
			gen tau = maxrand/1000000
		}

		sort studentno pref


		gen pf = 0 if subpri==1
		replace pf = tau if marpri==1
		replace pf = 1 if suppri==1

		bys studentno (pref) : gen MID = pf if _n==1
		forvalues i = 1/30 {
			bys studentno (pref) : replace MID = max(pf[`i'],MID[`i'-1]) if _n==`i'
		}

		bys studentno (pref) : gen asnprob = pf if _n==1
		bys studentno (pref) : replace asnprob = MID[_n] - MID[_n-1] if _n>1

		rename propose soffer		// simulated offer

		keep studentno pref pid asnprob soffer


		replace pid = substr(pid,1,7)
		collapse (sum) asnprob (min) pref (max) soffer, by(studentno pid)

		save "$stata_data_assignment/`y'/asnprob`g'.dta", replace

	}
}
